//
//  SYComposePictureView.swift
//  YANAWeibo
//
//  Created by mac on 16/5/20.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

// 重用标记
private let SYComposePictureViewCellIdentifier = "SYComposePictureViewCellIdentifier"

class SYComposePictureView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate {
    
    // 点击加号按钮的闭包
    var didSelectedAddImageClosure: (()->())?
    
    // 保存图片
    lazy var images: [UIImage] = [UIImage]()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        hidden = true
        // 注册cell
        registerClass(SYComposePictureViewCell.self, forCellWithReuseIdentifier: SYComposePictureViewCellIdentifier)
        // 设置数据源代理
        dataSource = self
        // 设置代理
        delegate = self
        backgroundColor = UIColor.orangeColor()
    }
    
    func addImage(image: UIImage) {
        hidden = false
        images.append(image)
        reloadData()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let itemMargin: CGFloat = 5
        let itemPicWith = (frame.width - 2 * itemMargin) / 3
        
        // 获取flowlayout
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSizeMake(itemPicWith, itemPicWith)
        
        flowLayout.minimumInteritemSpacing = itemMargin
        flowLayout.minimumLineSpacing = itemMargin
        
        
    }
    
    
     // MARK: --数据源代理方法
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let count = images.count
        if count == 0 || count == 9 {
            return count
        } else {
            return count + 1
        }
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(SYComposePictureViewCellIdentifier, forIndexPath: indexPath) as! SYComposePictureViewCell
        if indexPath.item < images.count {
            cell.image = images[indexPath.item]
        } else {
            // 显示加号按钮
            cell.image = nil
        }
        
        // 设置删除按钮的闭包
        cell.deleteButtonClosure = { [weak self] in
            // 如果数组中没有数据就不显示配图
            self?.images.removeAtIndex(indexPath.item)
            
            if self?.images.count == 0 {
                self?.hidden = true
            }
            
            self?.reloadData()
            
        }
        
        return cell
    }
    
     // MARK: --delegate 实现方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // 取消选中
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        
        // 如果当前item的索引扥与我们数组个数 就是加号图片
        if indexPath.item == images.count {
            // 回调闭包
            didSelectedAddImageClosure?()
        }
    }
    
}

// 自定义配图cell
class SYComposePictureViewCell: UICollectionViewCell {
    
    // 点击删除按钮的闭包
    var deleteButtonClosure: (()->())?
    
    // 设置图片
    var image: UIImage? {
        didSet {
            if image == nil {
                // 显示加号按钮
                imageView.image = UIImage(named: "compose_pic_add")
                // 添加高亮图片
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                deleteImageButton.hidden = true
            } else {
                imageView.image = image
                imageView.highlightedImage = nil
                deleteImageButton.hidden = false
            }
            
        }
    }
    
    // 显示图片
    private lazy var imageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
    
    /// 显示删除图片按钮
    private lazy var deleteImageButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: "deleteImageButtonClick", forControlEvents: .TouchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        return button
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(deleteImageButton)
        // 设置约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        deleteImageButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }
    }
    
    @objc private func deleteImageButtonClick() {
        deleteButtonClosure?()
    }
}

